const mdutil = require('md5util')
const header = {
  'Content-Type': 'application/json'
};

function APISDK(options) {
  if (!(this instanceof APISDK)) {
    return new APISDK(options)
  }
  options = options || {}
 
  if (!options.appKey || !options.secretKey) {
    throw new Error('appKey and secretKey are necessary!')
  }
  this.logDebug= options.logDebug||false;
  this.appKey = options.appKey
  this.secretKey = options.secretKey
  this.domain = options.domain || 'https://gw-api.pinduoduo.com/api/router'
  this.api = {
    'collectCarInfo': '/cm/collectCarInfo',//采集车辆信息
    'couponInfo': '/cm/couponInfo',//优惠券信息
    'getPayInfo': '/cm/getPayInfo',//获取预支付信息
    'userCouponList': '/cm/userCouponList',//我的优惠券
    'getUserScene': '/inner/getUserScene',//获取场景值信息
    'loginOrRegister': '/inner/loginOrRegister',//用户登录或注册
    'updateLateSceneInfo': '/inner/updateLateSceneInfo',//更新用户最近扫码渠道地址
    'getCouponCDResut': '/cm/getCouponCDResut',//查询优惠券核销结果
    'getCouponQRCode': '/cm/getCouponQRCode',//获取优惠券二维码


  
    login:'user/all/user/login',//登录
    exit: 'user/cm/user/exit',//退出
    sendMessage:'user/all/user/sendMessage',//发送短信
    balance:'migrate/cm/account/balance', // 余额
    genPayAuthCode:'trade/cm/genPayAuthCode', // 获取支付二维码 权益包
    orderByPayAuthCode:'trade/cm/orderByPayAuthCode', // 轮询二维码订单
    receivePackage:'coupon/cm/coupon/receivePackage', // 领券接口
    searchWriteOff:'coupon/cm/coupon/searchWriteOff', // 轮询二维码扫券结果
    sumDisAmount:'trade/cm/sumDisAmount', // 累计节省
    isInGasStation:'information/all/gasStation/isInGasStation', // 查询当前所在油站
    payMode:'information/cm/payMode/list', // 查询可用支付方式
    fuelPrepay: 'trade/cm/fuelPrepay', // 预支付

    getUserList: 'user/pf/user/getUserList',
    getUserInfo: 'user/inner/user/getUserInfo',
    userBindPlateNumber: 'user/inner/user/userBindPlateNumber',
    addCard: 'user/inner/user/escort/addCard',
    addUserPlatNumber: 'user/inner/user/addUserPlatNumber',
    authLoginByCode: 'user/all/user/authLoginByCode',
    updateUserStatus: 'user/pf/user/updateUserStatus',
    escortEquityBuy: 'trade/cm/escortEquityBuy',// 查询是否购买权益
    listCountCM: 'coupon/cm/coupon/listCountCM',// 用户优惠券统计
    pageList: 'coupon/cm/coupon/pageList',// 用户优惠券列表
    queryTradeOrder: 'protect/cm/queryTradeOrder',// 查询用户是否填写了车险
    searchGasStation:'information/all/gasStation/search/list',// 搜索油站'
    doFuelPay:'trade/cm/doFuelPay',

    'getopenid': '/user/getopenid',
    'addform': '/user/addform'
  }
}

let D = ['login', 'exit', 'sendMessage', 'balance', 'isInGasStation', 'payMode', 'fuelPrepay', 'getUserList', 'userBindPlateNumber', 'getUserInfo', 'authLoginByCode', 'addCard', 'addUserPlatNumber', 'updateUserStatus', 'pageList', 'sumDisAmount', 'escortEquityBuy', 'listCountCM', 'queryTradeOrder', 'searchGasStation', 'doFuelPay','genPayAuthCode'];
APISDK.prototype.send = function(url, params = {}, method = "post") {
  let that = this;
  let isurl=url.substr(0, 4).toLowerCase() == "http";
  if (!isurl) {
    url = this.domain + url
  }
  let token = wx.getStorageSync('apitoken')
  let power = wx.getStorageSync('power')
  if (power) {
    token = wx.getStorageSync('admintoken')
  }
  let webadmin = wx.getStorageSync('webadmin')
  let uid = wx.getStorageSync('uid')
  let header={
    'Content-Type': 'application/json',
    "source":'GDBJYY',
    "api-token":"9771a5c38646482581817cf01adf266"
  }

  // let header={
  //   sessionState:1,
  //   token:wx.getStorageSync('token'),
  //   userId:wx.getStorageSync('userId'),
  //   name:'ceshi',
  //   loginName:'testuser',
  //   phone:'',
  //   userName:'',
  //   nickName:'',
  //   role:'pf',
  //   source:'HAIKA',
  //   industryId:1,
  //   industryName:111,
  //   openid:'',
  // }
  // const args = {
  //   client_id: this.appKey,
  //   data_type: 'JSON',
  //   time: this.timestamp(),
  //   v: "V1",
  //   'type': method,
  //   uid: uid,
  //   token: token,
  //   webadmin: webadmin
  // }
  // let obj2 = Object.assign(args, params);
  // obj2.sign = this.sign(obj2);
  return new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      method: method,
      data: params,
      header:header,
      success: res => {
        if (res.data&&res.data.code == "000000") {
          resolve(res.data);
        } else {
          if (res.statusCode != 200) {
            throw new Error(JSON.stringify(res))
          }
          if (res.data.code == 500 || res.data.code =='user0020') {
            //   wx.reLaunch({     //跳转至指定页面
            //     url: '/pages/login/index'
            //   })
          } else if (that.logDebug){
            wx.showToast({
              title: res.data.msg,
              icon:'none'
            })
          }
          resolve(res.data)
        }
      },
      fail: e => {
        reject(e)
      }
    })
  })

}
// 签名算法
APISDK.prototype.sign = function(params) {
  let sorted = Object.keys(params).sort()
  let basestring = this.secretKey
  for (let i = 0, l = sorted.length; i < l; i++) {
    let k = sorted[i]
    console.log(i)
    basestring += k + params[k]
  }
  // console.log(params)
  basestring += this.secretKey
  return mdutil.md5(basestring).toUpperCase()
}
// 检验是否为空 参数检测
APISDK.prototype.notEmpty = function(obj) {
  if (!obj || obj == '' || obj == undefined) {
    return false;
  }
  if (Array.prototype.isPrototypeOf(obj) && obj.length === 0) {
    return false;
  }
  if (Object.prototype.isPrototypeOf(obj) && Object.keys(obj).length === 0) {
    return false;
  }
  return true;
}

APISDK.prototype.funcWhere = function() {
  let errs = new Error().stack
  let names = new Error().stack.match(/at (.*?) /g);
  let name = names[1].replace('at Object.', '').trim();
  return name;
}

APISDK.prototype.timestamp = function(d, options) {
  d = d || new Date()
  let timestamp = (d.getTime() / 1000).toFixed();
  return timestamp;
}
for (let i = 0; i < D.length; i++) {
  ! function(e) {
    APISDK.prototype[e] = function(data = {}, method = 'post') {
      let url = this.api[e];
      if (url) {
        return this.send(url, data, method)
      }
    };

  }(D[i])
}

module.exports = APISDK